<template>
	<view class="active">
		<view class="title" style="text-align: center;">
			<span style="font-size: 24px;">京东注册</span>
		</view>
		<uni-section>
			<view class="example">
				<!-- 基础用法，不包含校验规则 -->
				<uni-forms ref="baseForm" validate-trigger="blur" :modelValue="baseFormData">
					<uni-forms-item label="用户名" name="name" required>
						<uni-easyinput v-model="baseFormData.name" placeholder="请输入用户名" />
					</uni-forms-item>
					<uni-forms-item label="密码" name="password" required>
						<uni-easyinput v-model="baseFormData.password" type="password" placeholder="请输入密码" />
					</uni-forms-item>
					<uni-forms-item label="确认密码" name="confirmPassword" required>
						<uni-easyinput v-model="baseFormData.confirmPassword" type="password" placeholder="请确认密码" />
					</uni-forms-item>
					
				</uni-forms>
				<button type="primary" @click="submit('baseForm')">提交</button>
			</view>
		</uni-section>
	</view>
</template>

<script>
	import {
		registerLogin
	} from '../../apiRequest/login';

	export default {
		data() {
			return {
				baseFormData: {
					name: '',
					password: '',
					confirmPassword: '',
					code: '',
				},
				countdown: '',
				interval: null, // 定时器
				customRules: {
					name: {
						rules: [{
							required: true,
							errorMessage: '用户名不能为空'
						}]
					},
					password: {
						rules: [{
							required: true,
							errorMessage: '密码不能为空'
						}, {
							minLength: 6,
							maxLength: 20,
							errorMessage: '密码长度必须在6到20位之间'
						}]
					},
					confirmPassword: {
						rules: [{
							required: true,
							errorMessage: '确认密码不能为空'
						}, {
							minLength: 6,
							maxLength: 20,
							errorMessage: '密码长度必须在6到20位之间'
						}, {
							validateFunction: function(rule, value, data, callback) {
								console.log('确认密码输入值:', value);
								  console.log('原始密码值:', data);
								if (value !== data.password) {
									callback('两次输入的密码不一致')
								} else {
									return true;
								}
							},
							errorMessage: '确认密码与密码不一致'
						}]
					}
				}
			}
		},
		onReady() {
			// 需要在onReady中设置规则
			this.$refs.baseForm.setRules(this.customRules)
		},
		methods: {
			submit(ref) {
				this.$refs[ref].validate().then(res => {
					if (res) {
						registerLogin(this.baseFormData).then(regis => {
							console.log(regis);
							if (regis) {
								setTimeout(() => {
									uni.showModal({
										title: '注册成功',
										content: '点击确认去登录',
										showCancel: false,
										success() {
											uni.reLaunch({
												url: '/pages/login/login'
											});
										}
									});
								}, 2000);
							}
						}).catch(error => {
							console.error('注册失败:', error);
							uni.showToast({
								title: '注册失败',
								icon: 'none'
							});
						});
					}
				}).catch(err => {
					console.log('验证失败:', err);
				});
			}
		}
	}
</script>